from flask import Blueprint,jsonify,request
from db import db1
from utils.rs import rs
import datetime
from utils.myfile import get_data,post_data

bp_fiction = Blueprint('fiction',__name__)


# 登录
@bp_fiction.route('/flogin', methods=['POST', 'GET'])
def flogin():
    # 获取用户名密码
    data = get_data()
    resourcelist = []
    # 查询用户信息是否正确
    sql = "select * from euser where name='%s' and password='%s'"%(data['name'],data['password'])
    res = db1.find(sql)
    if res:
        roleid = res['role_id']
        # 根据角色id查询资源列表
        sql2 = "select * from erole_resources as er left join eresources as e on er.resourceid=e.id where er.roleid=%d"%(int(roleid))
        resourcelist = db1.find_all(sql2)
        # 判断role_id是否为2
        if int(roleid) == 2:
            rs.insert_set('auditidlist',res['id'])


    return jsonify({'code':200,'resourcelist':resourcelist,'msg':'登录成功','name':res['name'],'userid':res['id']})


import requests
@bp_fiction.route('/newsM',methods=['POST'])
def newsM():
    #获取参数
    data = get_data()
    #写入小说表
    sql = "insert into enews(title,userid) values('%s',%d)"%(data['title'],int(data['userid']))
    newsid = db1.update(sql)
    #审批，多个审批员1,2,3
    idlist = rs.find_set('auditidlist')
    #遍历
    min = 0
    #数量最少的
    auditid = -1
    sum=0
    if idlist:
        for i in idlist:
            #i代表审核人id
            key = 'audit%d'%(int(i))
            count = rs.list_len(key)
            if sum == 0:
                min = count
                auditid =i
            if min > count:
                min = count
                auditid =i
            sum+=1
        #加入审核人对应的任务列表
        if int(auditid)>0:
            rs.list_push('audit%d'%int(auditid),newsid)
        #调用django send发送消息
        requests.get('http://localhost:8000/sendmes1?audit_id='+str(auditid))
    else:
        return jsonify({"code":10010,'mes':'没有审核员'})
    return jsonify({"code":200})

#通过id获取小说信息
@bp_fiction.route('/getnews')
def getnews():
    id = request.args.get('id')
    sql = "select * from enews where id=%d"%(int(id))
    print(sql)
    news = db1.find(sql)
    return jsonify({"code":200,'news':news})

@bp_fiction.route('/audit_news')
def audit_news():
    # 审核通过-》更新小说表中审核状态，审核人
	# 			  更新积分纪录表
	# 			  更新用户表中总积分
    newsid = request.args.get('newsid')
    userid = request.args.get('userid')
    username = request.args.get('username')
    status = request.args.get('status')
    reason = request.args.get('reason')
    # sql = "select * from enews where id=%d"%(int(newsid))
    # news = db1.find(sql)
    now = datetime.datetime.now()
    sql = "update enews set status=%d,reason='%s',userid=%d,audit_user='%s',audit_time='%s' where id=%d"%(int(status),reason,int(userid),username,now,int(newsid))
    db1.update(sql)
    #加入积分记录表
    if int(status) == 2:
        #更新积分记录表
        sql1 = "insert into score_record(userid,score,ctime) values(%d,%d,'%s')"%(int(userid),3,now)
        db1.update(sql1)
        #更新用户总积分
        sql2 = "update euers set score=score+3 where id=%d"%(int(userid))
        db1.update(sql2)
    return jsonify({"code":200})


#通过
@bp_fiction.route('/fpass')
def fpass():
    id = request.args.get('id')
    sql = """update novel set status=2 where id = %d"""%int(id)
    db1.update(sql)
    sql3 = """select * from novel where id = %d"""%int(id)
    res = db1.find(sql3)
    sql2 = """select * from users where id = %d"""%int(res['userid'])
    ress = db1.find(sql2)
    jf = int(ress['total']) + 2
    sql1 = """update users set  total = %d where id = %d"""%(jf,int(res['userid']))
    db1.update(sql1)
    return jsonify({"code":200})


#不通过
@bp_fiction.route('/nopass')
def nopass():
    id = request.args.get('id')
    sql = """update novel set status=3 where id = %d""" % int(id)
    db1.update(sql)
    return jsonify({"code": 200})


@bp_fiction.route('/addtotal',methods = ['POST','GET'])
def addtotal():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into total(name,price,kc,earned) values('%s',%d,%d,%d)"""%(data['name'],int(data['price']),int(data['kc']),int(data['earned']))
        db1.update(sql)
        return jsonify({'code':200})